<template>
  <el-dialog v-model="dialogVisible" title="忘记密码" width="400px" :close-on-click-modal="false">
    <el-form :model="forgotForm" :rules="rules" ref="forgotFormRef" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input 
          v-model="forgotForm.username" 
          placeholder="请输入用户名"
          :prefix-icon="User"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input 
          v-model="forgotForm.phone" 
          placeholder="请输入手机号"
          :prefix-icon="Phone"
        />
      </el-form-item>
      <el-form-item v-if="password" label="您的密码">
        <el-input 
          :value="password" 
          readonly
          type="password"
        >
          <template #append>
            <el-button @click="copyPassword">复制</el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">找回密码</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { User, Phone } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: Boolean
})

const emit = defineEmits(['update:modelValue'])

const userStore = useUserStore()
const dialogVisible = ref(props.modelValue)
const loading = ref(false)
const forgotFormRef = ref()
const password = ref('')

const forgotForm = ref({
  username: '',
  phone: ''
})

const validatePhone = (rule, value, callback) => {
  const phoneReg = /^1[3-9]\d{9}$/
  if (!phoneReg.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ]
}

// 清空表单的方法
const resetForm = () => {
  forgotForm.value = {
    username: '',
    phone: ''
  }
  password.value = ''
  forgotFormRef.value?.resetFields()
}

watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
  // 弹窗关闭时清空表单
  if (!newVal) {
    resetForm()
  }
})

watch(dialogVisible, (newVal) => {
  emit('update:modelValue', newVal)
  // 弹窗关闭时清空表单
  if (!newVal) {
    resetForm()
  }
})

const handleSubmit = async () => {
  await forgotFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const result = await userStore.forgotPasswordAction(forgotForm.value)
        password.value = result.password
        ElMessage.success('密码找回成功')
      } catch (error) {
        ElMessage.error('找回失败: ' + error.message)
      } finally {
        loading.value = false
      }
    }
  })
}

const copyPassword = () => {
  navigator.clipboard.writeText(password.value)
  ElMessage.success('密码已复制到剪贴板')
}

const handleCancel = () => {
  dialogVisible.value = false
}
</script>